package com.ee.chat.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.IKeyWordService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.SysKeyWordLibMapper;
import com.ee.chat.common.entity.SysKeyWordLib;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.SensitiveWordUtil;
import com.ndhutu.ee.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author AppiJ
 * @Date 2020/4/23 14:43
 */
@Service
public class KeyWordServiceImpl implements IKeyWordService {

    @Resource
    SysKeyWordLibMapper keyWordLibMapper;
    @Resource
    IOperationService operationService;
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    ProducerBean producer;

    @Value("${ali.rocketmq.word.topic}")
    String word_topic;
    @Value("${ali.rocketmq.word.tag2}")
    String wordTag;

    @Resource
    MyNeteaseApp app;

    /**
     * 获取关键词列表
     * @Author AppiJ
     * @Date 2020/4/23 14:51
     * @param
     * @return
     */
    @Override
    public Result list(HttpServletRequest request, String keyword, Integer status, String time, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(keyword) && StringUtil.isEmpty(time) && status == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/keyWord/viewList")){
                data.put("keyWordLibs", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<SysKeyWordLib> p = new Page<>(page, limit);
        IPage<SysKeyWordLib> iPage = keyWordLibMapper.list(p, keyword, status, beginTime, endTime);
        List<SysKeyWordLib> keyWordLibs = iPage.getRecords();

        data.put("keyWordLibs", keyWordLibs);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查询关键词列表数据");

        return Result.returnSuccess(data);
    }

    /**
     * 添加关键词
     * @Author AppiJ
     * @Date 2020/4/23 15:10
     * @param
     * @return
     */
    @Override
    public Result add(HttpServletRequest request, String word) throws Exception {

        SysKeyWordLib keyWordLib = new SysKeyWordLib();
        keyWordLib.setWord(word);
        keyWordLibMapper.insert(keyWordLib);

        Object keyWordObj = redisTemplate.opsForHash().get("data", "keyWord");
        Map<String, Object> keyWordMap = JSONObject.parseObject(keyWordObj+"", Map.class);
        keyWordMap = SensitiveWordUtil.addWord(keyWordMap, word);
        //缓存DFA词库
        redisTemplate.opsForHash().put("data", "keyWord", JSONObject.toJSONString(keyWordMap));

        //生产词匹配消息
        Message message = new Message(word_topic, app.getIdPrefix() + "-" + wordTag, JSONObject.toJSONString(new HashMap<>()).getBytes());
        producer.sendOneway(message);

        operationService.addOperationLog(request, "添加关键词，【" + word + "】");

        return Result.returnSuccess(null);
    }

    /**
     * 修改关键词状态
     * @Author AppiJ
     * @Date 2020/4/9 15:32
     * @param
     * @return
     */
    @Override
    public Result updateStatus(HttpServletRequest request, Integer id) throws Exception {

        SysKeyWordLib keyWordLib = keyWordLibMapper.selectById(id);
        if(keyWordLib.getStatus() == 0){
            keyWordLib.setStatus(1);
        }else {
            keyWordLib.setStatus(0);
        }
        keyWordLibMapper.updateById(keyWordLib);

        List<String> words = keyWordLibMapper.getWords();
        Map<String, Object> keyWordMap = SensitiveWordUtil.init(new HashSet<>(words));

        //缓存DFA词库
        redisTemplate.opsForHash().put("data", "keyWord", JSONObject.toJSONString(keyWordMap));

        //生产词匹配消息
        Message message = new Message(word_topic, app.getIdPrefix() + "-" + wordTag, JSONObject.toJSONString(new HashMap<>()).getBytes());
        producer.sendOneway(message);

        operationService.addOperationLog(request, "修改关键词状态，id：" + id);

        return Result.returnSuccess(null);
    }
}
